#include "ft_font.h"
// including the free type header here

#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H

// multi-stuff 
#include "xworker_single_queue.h"
#include "xkillable_task.h"
#include "xworker.h"
#include "xloop_sync.h"

#include "xfont.h"
#include "xtimer.h"
#include "xstring.h"

namespace {
  using namespace xge;
  using namespace xge::xge_internal;
  // FFT font manager
  class FTFontManager : public FontManager , public LoopSync {
  public:
    virtual FontPtr CreateFont( const String* resource_name );
    virtual FontPtr CreateFont( void* buffer , size_t size );
  private:
    virtual void LoopTicking( const Timer::tick_t& diff_time );
    friend class LoopSync;
  public:
    // Initialize the font manager here 
    // This initialization call will make the ft initialized
    // and fft internal library will be allocated 
    bool InitializeFT() ; 
  private:
    bool DestroyFT();
  private:
    // The free type library
    FT_Library ft_lib_;
    bool ft_initialized_;
    // Using a back queue to deal with thread stuff 
    typedef Worker< WorkerSingleQueue > FTFontTaskQueue;
    FTFontTaskQueue task_queue_;
  };

  bool FTFontManager::InitializeFT() {
    // Initialize the free type library
    FT_Error error = FT_Init_FreeType(&ft_lib_);
    if( error ) {
      // print out the error string here
      SYS_LOG(PANIC,true,_xT("Can not create free type library!"));
      return false;
    }
    // Now we initialize the queue stuff here
    if( !task_queue_.Dispatch(_xT("FreetypeThread"),"FreetypeThread") ) {
      // now failed to load the back thread 
      FT_Done_FreeType(ft_lib_);
      return false;
    }
    ft_initialized_ = true;
    SYS_LOG(INFO,false,_xT("The FreeType font manager has been set up!"));
    return true;
  }


}